<template>
  <div>
    <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
      <el-form :model="queryParams" ref="personageQueryForm" :inline="true" label-width="auto" label-position="left"
        :rules="shopProductRules">
        <el-form-item label="商品ID" prop="param.newIDs">
          <el-input type="number" v-model.trim="queryParams.param.newIDs" placeholder="请输入" clearable :min="1" />
        </el-form-item>
        <el-form-item label="商品名" prop="name">
          <el-input style="width: 200px" v-model.trim="queryParams.param.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="来源货币" prop="currencyId">
          <el-select style="width: 200px" v-model="queryParams.param.currencyId" placeholder="请选择" clearable>
            <el-option v-for="dict in sys_currency_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="来源网站" prop="collectionSiteId">
          <el-select style="width: 200px" v-model="queryParams.param.collectionSiteId" placeholder="请选择" clearable>
            <el-option v-for="dict in host_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-tree-select style="width: 200px" v-model="queryParams.param.categoryId" :data="categoryOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择"
            check-strictly clearable />
        </el-form-item>
        <el-form-item label="语言" prop="translatedLanguageId">
          <el-select style="width: 200px" v-model="queryParams.param.translatedLanguageId" placeholder="请选择" clearable>
            <el-option v-for="dict in sys_language_type" :key="dict.id" :label="dict.description"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="已发布站点" prop="publishedSiteIds">
          <el-select style="width: 200px" v-model="queryParams.param.publishedSiteIds" placeholder="请选择" clearable
            multiple>
            <el-option v-for="dict in webSiteList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
    </searchBox>

    <el-button type="primary" plain @click="handleBatch(1)">批量发布</el-button>
    <el-button type="primary" plain @click="handleBatch(0)">批量下架</el-button>
    <el-button type="primary" plain @click="handleBatch(2)">批量改价</el-button>


    <el-table :data="productList" @selection-change="handleSelectionChange" ref="productListRef"
      style="height: calc(100vh - 380px)" v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="100" />
      <el-table-column label="商品图" align="center" width="120">
        <template #default="scope">
          <image-preview :src="scope.row.newImage" :width="75" :height="75" />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name" width="300">
        <template #default="scope">
          <el-link :href="scope.row.rawUrl" target="_blank" :underline="false">{{
            scope.row.name
          }}</el-link>
          <div style="display: flex;flex-direction: column;">
            <div class="mb8">
              <el-button type="primary" plain size="small">
                {{ scope.row.languageName }}
              </el-button>
              <el-link :href="scope.row.collectionSiteUrl" target="_blank" :underline="false"
                style="margin-left: 10px;">{{ scope.row.collectionSiteName }}</el-link>
            </div>
            <div>
              <el-tag type="primary" v-if="scope.row.newRawCategories?.length">
                <el-text style="max-width: 150px;" truncated> {{ scope.row.newRawCategories[0]?.name }}</el-text>
              </el-tag>

              <el-tooltip effect="dark" placement="top-start">
                <template #content>
                  <el-space spacer=" " wrap>
                    <div v-for="item in scope.row.newRawCategories" :key="item.id">
                      <el-text style="color: #fff;" v-if="item.name">{{ item.name }}</el-text>
                    </div>
                  </el-space>
                </template>
                <el-tag type="primary" style="margin-left: 10px;" v-if="scope.row.newRawCategories?.length > 1">More {{
                  scope.row.newRawCategories?.length }}
                </el-tag>
              </el-tooltip>
            </div>

          </div>
        </template>
      </el-table-column>
      <el-table-column label="采集价格" width="150">
        <template #default="scope">
          <el-tooltip placement="top">
            <template #content>
              <div>
                {{ scope.row.currencyName }}：{{
                  scope.row.price }} {{ scope.row.symbol
                }}
                <br />
                人民币：{{ scope.row.cnyprice }} ￥
              </div>
            </template>
            <div>
              {{ scope.row.price }} {{ scope.row.symbol }}
              <br />
              <el-text type="info"> {{ scope.row.cnyprice }} ￥</el-text>
            </div>

          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="已翻译语言" prop="translatedLanguageNameList" />
      <el-table-column label="已发布站点">
        <template #default="scope">
          <el-text>
            {{
              "共发布" +
              (scope.row.publishedSiteIds
                ? scope.row.publishedSiteIds.length
                : 0) +
              "个站点"
            }}</el-text>
          <el-button @click="viewDetail(scope.row)" link type="primary"
            v-if="scope.row.publishedSiteIds">查看更多</el-button>
        </template>
      </el-table-column>
   

      <el-table-column fixed="right" label="操作" align="center" width="270px">
        <template #default="scope">
          <div class="Operation">
            <el-button link type="primary" @click="publicIncident(scope.row, 0)">编辑</el-button>
            <el-button link type="primary" @click="publicIncident(scope.row, 1)">发布</el-button>
            <el-dropdown @command="(command) => commandHandler(scope.row, command)">
              <span class="el-dropdown-link">
                更多
                <el-icon>
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <div v-for="item in choseIncident" :key="item.id">
                    <el-dropdown-item :command="item" v-if="handleShow(item.id, scope.row)">
                      <el-text :type="item.type">{{
                        item.title }}</el-text>
                    </el-dropdown-item>
                  </div>

                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination :total="total" :limit="queryParams.pageSize" :page="queryParams.pageNum" @pagination="handlePageChange">
    </Pagination>

    <publicSite :dialogVisible="viewDetailVisible" @handleListClose="handleListClose" :listItem="publicItem">
    </publicSite>
    <ProductPrice :dialogPrice="dialogPrice" :Item="publicItem" @handlePriceClose="handlePriceClose"
      @handlePriceSure="handlePriceSure"></ProductPrice>
    <ProductEdit :publicFrom="publicItem" @handleEditClose="handleEditClose" :dialogEdit="dialogEdit"></ProductEdit>
    <PublicSource :PublicDialog="PublicDialog" :publicFrom="publicItem" @handlePublicSure="handlePublicSure"
      @handlePublicClose="handlePublicClose"></PublicSource>
  </div>
</template>

<script setup>
import { ref, h, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import publicSite from "@/views/publicSite";
import ProductPrice from "./components/productPrice.vue";
import ProductEdit from "./productEdit.vue";
import PublicSource from "./publicPage/publicSource.vue";


const { proxy } = getCurrentInstance();
const router = useRouter();
const sys_currency_code = ref([]); //来源货币列表数据
const sys_language_type = ref([]); //获取语言类别
const host_type = ref([]); //来源网站
const webSiteList = ref([]); //发布站点数据
const dialogEdit = ref(false)
const loading = ref(true)
const PublicDialog = ref(false)//默认货源弹出框是false


const choseIncident = ref([
  {
    type: "primary",
    title: "价格处理",
    id: 2,
  },
  {
    type: "primary",
    title: "货源",
    id: 1,
  },
  {
    type: "primary",
    title: "下架",
    id: 3,
  },
  // {
  //   type: "danger",
  //   title: "删除",
  // },
]);
const viewDetailVisible = ref(false);
const dialogPrice = ref(false);//改价弹窗

const total = ref(0); // 总条数
const productList = ref([]); // 产品中心表格数据

// 类别管理下拉框
const categoryOptions = ref([]);
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    name: "", //产品名称
    currencyId: null, //来源货币
    collectionSiteId: null, //来源网站
    categoryId: null, //商品分类
    translatedLanguageId: null, //已翻译语言
    publishedSiteIds: [],//发布站点id
    ids: [],
    newIDs: null
  },
});
const publicItem = ref({}); //公共赋值对象

onMounted(() => {
  getList();
  getLanguage(); //获取下拉数据
});
/** 搜索按钮操作 */
const handleQuery = () => {
  proxy.$refs["personageQueryForm"].validate((valid) => {
    if (!valid) return
    if (queryParams.value.param.newIDs) {
      queryParams.value.param.ids = []
      queryParams.value.param.ids.push(queryParams.value.param.newIDs)
      queryParams.value.param.ids = queryParams.value.param.ids.map(Number)
    }
    getList();
  })
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    param: {
      name: "", //产品名称
      currencyId: null, //来源货币
      collectionSiteId: null, //来源网站
      categoryId: null, //商品分类
      translatedLanguageId: null, //已翻译语言
      publishedSiteIds: [],//发布站点id
      ids: [],
      newIDs: ''
    },
  };
  getList();
};
/** 查询产品中心列表 */
const getList = () => {
  product.general
    .productList({
      data: queryParams.value,
    })
    .then((res) => {
      total.value = res.total;
      loading.value = false
      if (res.data?.length) {
        res.data = res.data.map(code => {
          return {
            ...code,
            newRawCategories: code.rawCategories || [],
            newImage: handleImage(code)
          }
        })
      }
      productList.value = res.data;
      console.log(res.data);
      getProductIds();
    });
};
// 查看更多站点
const viewDetail = (row) => {
  row = {
    ...row,
    websiteIds: row.publishedSiteIds
  }
  publicItem.value = row;
  viewDetailVisible.value = true;
};
// 查看站点取消事件
const handleListClose = () => {
  viewDetailVisible.value = false;
};
const publicIncident = (row, index) => {
  // 发布
  if (index === 1) {
    let from = {
      newList: [],
    };
    from.newList.push(row.id);
    sessionStorage.setItem("productListIds", JSON.stringify(from.newList));
    router.push({ path: `product/publish` });
  } else {
    publicItem.value = row;
    dialogEdit.value = true;
  }
};
const commandHandler = (row, command) => {
  if (command.id === 1) { // 货源
    publicItem.value = row;
    PublicDialog.value = true;
   
  } else if (command.id === 2) {  // 改价
    publicItem.value = row;
    dialogPrice.value = true;
  } else if (command.id === 3) { // 下架
    let from = {
      newList: [],
    };
    from.newList.push(row.id);
    sessionStorage.setItem("productListIds", JSON.stringify(from.newList));
    console.log(sessionStorage.getItem("productListIds"));
   
    router.push({
      path: `product/undercarriage`,
    });
  }
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  let from = {
    newList: [],
  };
  from.newList = selection.map((item) => item.id);
  sessionStorage.setItem("productListIds", JSON.stringify(from.newList));
};
const getLanguage = () => {
  // 来源货币
  product.currency.currencyList().then((res) => {
    if (res.data?.length) {
      res.data = res.data.map((code) => {
        return {
          ...code,
          label: code.description,
          value: code.id,
        };
      });
    }
    sys_currency_code.value = res.data;
  });
  // 获取语言
  product.language.languageList().then((res) => {
    sys_language_type.value = res.data;
  });
  // 来源网站
  product.collectionsite
    .collectionsiteList({
      data: {
        pageNum: 1,
        pageSize: 999,
      },
    })
    .then((res) => {
      if (res.data?.length) {
        res.data = res.data.map((code) => {
          return {
            ...code,
            label: code.name,
            value: code.id,
          };
        });
      }
      host_type.value = res.data;
    });

  // 商品分类
  product.productcategory
    .productcategoryGetcategories({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          languageId: 1
        },
      },
    })
    .then((response) => {
      categoryOptions.value = response.data;
    });
  site.general
    .sitewebsiteList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          status: 1, //状态
          publishStatus: ['Succeed', 'Failed'],
        },
      },
    })
    .then((res) => {
      webSiteList.value = res.data;
    })
};
// 分页
const handlePageChange = (newPage) => {
  queryParams.value.pageNum = newPage.page;
  queryParams.value.pageSize = newPage.limit;
  getList();
};
const handleBatch = (index) => {
  let newListIds = JSON.parse(sessionStorage.getItem("productListIds"));
  if (!newListIds || !newListIds.length) return proxy.$modal.msgWarning("请勾选");
  if (index === 1) {
    router.push({ path: `product/publish` });
  } else if (index === 2) {
    publicItem.value = { newProductIds: newListIds };
    dialogPrice.value = true;
  } else {
    router.push({
      path: `product/undercarriage`,
    });
  }
};
const getProductIds = () => {
  let newListIds = JSON.parse(sessionStorage.getItem("productListIds"));
  console.log(newListIds), '[[[[[[[]]]]]]]'
  if (!newListIds) return;
  newListIds.forEach((e) => {
    const existingRow = productList.value.find((item) => item.id === e);
    if (existingRow) {
      proxy.$refs["productListRef"].toggleRowSelection(existingRow, true);
    }
  });
};



const handlePriceClose = () => {
  publicItem.value = {};
  dialogPrice.value = false;
}
const handlePriceSure = () => {
  getList()
}
const handleImage = (row) => {
  var imageExtensionsRegex = /^https?:\/\//i;
  if (!imageExtensionsRegex.test(row.mainImage)) {
    return row.host
  } else {
    return row.mainImage
  }
}
const handleEditClose = () => {
  publicItem.value = {};
  dialogEdit.value = false
}
const handlePublicClose = () => {
  publicItem.value = {};
  PublicDialog.value = false
}
const handlePublicSure = () => {
  publicItem.value = {};
  PublicDialog.value = false
}
const handleShow = (item, row) => {
  if (item == 3) {
    if (row.publishedSiteIds && row.publishedSiteIds.length > 0) {
      return true
    } else {
      return false
    }
  } else {
    return true
  }

}
const shopProductRules = reactive({
  'param.newIDs': [
    {
      pattern: /^[1-9]\d*$/,
      message: "请正确输入ID",
      trigger: "blur",
    },
  ],
})
</script>
<style lang="scss" scoped>
.Operation {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>